/*
 * @Author: Gigi 1517618446@qq.com
 * @Date: 2022-08-22 15:23:30
 * @LastEditors: Gigi 1517618446@qq.com
 * @LastEditTime: 2022-09-08 00:04:47
 * @FilePath: \ws\js\12_CSS_购物车页面示例.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

noOrders();
zongjia();
loadshopcar();
//
var id;

/*$(".gopay").click(function () {
    var token = localStorage.getItem("token");
    $.ajax({
        type: "get",
        url: "http://localhost:8081/demo/spikeProduct/goConfirm",
        data:{
            "proId":id,
            "token":token
        }
    })
})*/

function loadshopcar(){
    console.log("shopcar!!!")
    var token = localStorage.getItem("token");
    console.log("token:"+token)
    $.ajax({
        type:"get",
        url:"http://localhost:8081/demo/cart/shopcart",
        headers:{"token":token},
        success:function (result){
            console.log("111222");
            console.log(result)
            var data = result.data;
            console.log(data);

            var user = data.users;
            var cartNum = data.cartNum;
            var productList = data.productList;
            var details = data.prodetails;
            var cartlist = data.cartList;

            $("#myul").html("");


            for (var i=0;i<cartNum;i++){
                var prodetail = details[i];
                var prolist = productList[i];
                var car = cartlist[i];
                var proEle = '<li class="pro">\n' +
                    '                <!-- (1).选择框 -->\n' +
                    '                <input type="checkbox" class="selectBtn">\n' +
                    '\n' +'<input type="hidden" name="productId" value="'+prolist.productId+'">'+
                    '                <!-- (2).商品图片 -->\n' +
                    '                <a href="../product_show/detail.html"><img src="../images/shopcar_pro1.jpg" style="position:absolute; left:40px; margin-top: 25px;"></a>\n' +
                    '\n' +
                    '                <!-- (3).商品名字 -->\n' +
                    '                <div class="name">\n' +
                    '                    <a href="../product_show/detail.html"><p> '+prodetail +
                    '                    </p></a>\n' +
                    '\n' +
                    '                    <!-- 优惠券 -->\n' +
                    '                    <a href="../personal/myCoupon.html"><input type="submit" value="优惠券 >" style="width: 65px; height: 20px; background-color: rgb(230, 0, 0); color: white; line-height: 20px; text-align: center;border: none; border-radius: 2px; font-size: 13px; margin-top: 7px; cursor: pointer;" class="youhuiquanBtn"></a>\n' +
                    '                </div>\n' +
                    '\n' +
                    '                <!-- (4).商品价格 -->\n' +
                    '                <div class="price">\n' +
                    '                    <span>￥</span>\n' +
                    '                    <span>'+prolist.productPrice+'</span>\n' +
                    '                </div>\n' +
                    '\n' +
                    '                <!-- (5).商品数量 -->\n' +
                    '                <div class="count">\n' +
                    '                    <!-- - -->\n' +
                    '                    <input type="submit" value="-" style="width: 20px;height: 20px;float: left; border: 1px solid lightgray;">\n' +
                    '                    <!-- text -->\n' +
                    '                    <input type="text" value = "'+car.productNum+'" style="width: 40px;height:20px;float: left; border: 1px solid lightgray; outline: none; text-align: center;">\n' +
                    '                    <!-- + -->\n' +
                    '                    <input type="submit" value="+" style="width: 20px;height: 20px;float: left; border: 1px solid lightgray;">\n' +
                    '                </div>\n' +
                    '\n' +
                    '                <!-- (6).小计 -->\n' +
                    '                <div class="pro-xiaoji">\n' +
                    '                    <span>￥</span>\n' +
                    '                    <span>'+car.productNum*prolist.productPrice+'</span>\n' +
                    '                </div>\n' +
                    '\n' +
                    '                <!-- (7).操作 -->\n' +
                    '                <div class="pro-caozuo">\n' +
                    '                    <button class="del" data-toggle="modal" data-target="#myModal1">删除</button>\n' +
                    '                </div>\n' +
                    '            </li>';
                $("#myul").append(proEle);
            }



        }
    })

}

document.querySelector(".gopay").onclick = function(){
    var token = localStorage.getItem("token");
    console.log("token:"+token)


}





var delliele;
var updateele;
var delallli;
document.querySelector("#shopcar").onclick = function(event){
    var ele = event.target;
   
    //"+"
    if(ele.nodeName == "INPUT" && ele.value == "+"){
        // (2).通过 + 标签位置，定位到 数量位置，count++;
        var count = ele.previousElementSibling.value;
        // (3).覆盖原来值
        ele.previousElementSibling.value = ++count;
        console.log("数量：" + count);

        //(4).获得单价
        var unitPrice = ele.parentElement.previousElementSibling.children[1].innerText;
        console.log("单价：" + unitPrice);

        //(5).修改小计的值
        var xiaoji = ele.parentElement.nextElementSibling.children[1].innerText = (count * unitPrice).toFixed(2);
        console.log("小计：" + xiaoji);



        zongjia();
    }
    
    //"-"
    else if(ele.nodeName == "INPUT" && ele.value == "-"){
        // (2).通过 - 标签位置，定位到 数量位置，count++;
        var count = ele.nextElementSibling.value;
        // (3).覆盖原来值
        if(count == 1) return;
        ele.nextElementSibling.value = --count;
        console.log("--数量：" + count);

        //(4).获得单价
        var unitPrice = ele.parentElement.previousElementSibling.children[1].innerText;
        console.log("--单价：" + unitPrice);

        //(5).修改小计的值
        var xiaoji = ele.parentElement.nextElementSibling.children[1].innerText = (count * unitPrice).toFixed(2);
        console.log("--小计：" + xiaoji);

        zongjia();
    }
    
    //全选与其他选择框的连带作用
    else if(ele.nodeName == "INPUT" && ele.type == "checkbox"){
        var checkedBtnArr = document.querySelectorAll(".selectBtn");
        console.log("1111111111:" + checkedBtnArr);
        var unSelectCount = 0;
        var selectedCount = 0;

        for(var i = 0; i <checkedBtnArr.length; i++){
            if(!checkedBtnArr[i].checked){
                checkedBtnArr[i].parentElement.className = "pro";
                unSelectCount++;
            }

            if(checkedBtnArr[i].checked){
                checkedBtnArr[i].parentElement.className = "pro it";
                selectedCount++;

                //拿id
                var token = localStorage.getItem("token")
                var proId = checkedBtnArr[i].nextElementSibling.value;
                id =parseInt(proId);
                id+=1000;
                console.log("id：" + id);
                $(".gopay").attr("href","http://localhost:8081/demo/spikeProduct/goConfirm?proId="+id+"&token="+token);

                // var proCount = ele.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling;
                // console.log("count：" + proCount);
            }
        }

        if(selectedCount == checkedBtnArr.length){
            document.querySelector(".check").checked = true; //如果选择的个数 == 数组长度 --> 让全选框checked
        }else if(unSelectCount <= checkedBtnArr.length){
            document.querySelector(".check").checked = false; //如果选择的个数 <= 数组长度 --> 让全选框checked 取消
        }

        zongjia();
    }

    //点击删除，先获取要删除的 li 元素，用于一会的确认操作
    if(ele.nodeName == "BUTTON" && ele.className == "del"){
        delliele = ele.parentElement.parentElement;
        updateele = ele.parentElement;
     }
 
     //确认删除操作
     if(ele.nodeName == "BUTTON" && ele.className == "yes"){
         $("#myModal1").modal("hide");
         delone();
         noOrders();
      }

      //点击清空购物车，先获取先获得所有节点元素，用于一会的确认操作
      if(ele.nodeName == "BUTTON" && ele.className == "delall"){
        delallli = document.querySelector("#myul");
      }

      //确认清空操作
      else if(ele.nodeName == "BUTTON" && ele.className == "yep"){
        $("#myModal2").modal("hide");
        delall();
        if(document.querySelector("#myul") == null)
        document.querySelector(".pro-list").innerHTML = '<div class="noOrder"><p class="words">没有订单哦~<br>快去首页逛逛吧！</p></div>';
      }
      
    }

//全选按钮
document.querySelector(".check").onclick = function(){
    var allCheckBtn = document.querySelectorAll(".selectBtn");
    for(var i =0;i<allCheckBtn.length;i++){
          allCheckBtn[i].checked = document.querySelector(".check").checked;
          allCheckBtn[i].parentElement.className = "pro it";

          if(!document.querySelector(".check").checked) allCheckBtn[i].parentElement.className = "pro";
    }
    zongjia();
};

//计算总价业务： + - 每个元素的选择框 全选框 最开始默认勾选
function zongjia(){
    var totalCount = 0;
    var totalPrice = 0;

    //(1).获得所有已勾选的商品的 checkbox (checked)
   var checkedBtnArr = document.querySelectorAll(".selectBtn");
   
   for(var i = 0; i < checkedBtnArr.length; i++){
    if(checkedBtnArr[i].checked){
        
        //(2).获得所有的已选中的商品 数量 累加
      var childrenArr = checkedBtnArr[i].parentElement.children;
      var childrenArr1  = childrenArr[childrenArr.length-3].children;
      var count = childrenArr1[childrenArr1.length-2].value;

      //(3). 获得所有的已选中的商品 小计 累加
      var childrenArr3 = childrenArr[childrenArr.length-2].children;
      var xiaoji = childrenArr3[childrenArr3.length-1].innerText;

      totalCount += parseInt(count);
      totalPrice += parseFloat(xiaoji);

      console.log("已选择n件商品：" + totalCount);
      console.log("总价：" + totalPrice);
      console.log(typeof(totalPrice))
    }
   }

    //(4) 修改底部的已选中的商品数量
    document.querySelector(".pro-count .selectCount").innerText = totalCount;
    
    //(5) 修改底部的总价
    document.querySelector(".summoney .totalPrice").innerText = totalPrice.toFixed(2);
}

//全部商品个数 == li的个数
var proArr = document.querySelectorAll(".pro");
document.querySelector(".num").innerText = proArr.length;

//如果无订单，显示无订单提醒
function noOrders(){
    var myulele = document.querySelector("#myul");
    if(myulele.innerText == '' || (myulele.childNodes[0].nodeName == '#text' && myulele.childNodes.length == 1))
    myulele.innerHTML = '<div class="noOrder"><p class="words">没有订单哦~<br>快去首页逛逛吧！</p></div>';
}

//删除一个 li操作
function delone(){      
    //商品个数 -1
     document.querySelector(".num").innerText = document.querySelector(".num").innerText -1;

     //总价 - 被删商品小计
     var delPrice = updateele.previousElementSibling.children[1].innerText;
     if(document.querySelector(".totalPrice").innerText != 0)
     document.querySelector(".totalPrice").innerText -= delPrice;

     //已选商品个数 - 被删商品数量
     var delCount = updateele.previousElementSibling.previousElementSibling.children[1].value;
     if(document.querySelector(".selectCount").innerText != 0)
     document.querySelector(".selectCount").innerText -= delCount;

     //删除 li结点
     delliele.remove();

     //如果商品个数为 0，全选取消
      if(document.querySelector(".num").innerText == 0) 
      document.querySelector(".check").checked = false;
}

//删除所有 li操作
function delall(){
    if(document.querySelector(".num").innerText != 0){
      //清空 ul的所以结点
      delallli.remove();

      //商品个数归 0
      document.querySelector(".num").innerText = 0;

      //总价归 0
      document.querySelector(".totalPrice").innerText = 0;

      //已选商品个数归 0 
      document.querySelector(".selectCount").innerText = 0;

      //全选取消
     document.querySelector(".check").checked = false;
  }
}

  